package com.powerbank.devicecenter.mqtt;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;

/**
 * MQTT配置类
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class MqttConfig {

    private final MqttProperties mqttProperties;

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        
        options.setServerURIs(new String[]{mqttProperties.getBroker().getUrl()});
        options.setUserName(mqttProperties.getBroker().getUsername());
        options.setPassword(mqttProperties.getBroker().getPassword().toCharArray());
        options.setKeepAliveInterval(mqttProperties.getBroker().getKeepAlive());
        options.setCleanSession(mqttProperties.getBroker().getCleanSession());
        options.setConnectionTimeout(30);
        options.setAutomaticReconnect(true);
        
        factory.setConnectionOptions(options);
        return factory;
    }
}